<template>
  <div class="commen-container">
    <h1>课堂管理</h1>
    <div class="commen-header">
      <div class="header-block ">
        <el-input
          placeholder="请输入要搜索的课堂名称"
          v-model="formData.semester_name" size="10">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-input
          placeholder="请输入要搜索的教师姓名"
          v-model="formData.username" size="10">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <div>
          <label>课堂开始时间: </label>
          <el-date-picker
            v-model="times"
            type="daterange"
            range-separator="To"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="handleTimes"
            :picker-options="pickerOptions"
            clearable
          />
        </div>
        <el-button type="primary" size="normal" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
        <el-button size="normal" icon="el-icon-refresh" @click="handleClear">
          重置
        </el-button>
      </div>
      <div>
        <el-button type="danger" size="normal" icon="el-icon-delete-solid" @click="handleBatchDelete">
          批量删除
        </el-button>
        <!--        <el-button type="success" size="normal" icon="el-icon-circle-plus" @click="">-->
        <!--          新增-->
        <!--        </el-button>-->
      </div>
    </div>
    <div v-if="loading" class="juzhong">
      <span><i class="el-icon-loading"></i>
      加载中</span>
      <el-divider></el-divider>
    </div>
    <div v-else-if="!tableData || tableData.length < 1" class="juzhong">
      <span><i class="el-icon-info"></i>
      暂无数据</span>
      <el-divider></el-divider>
    </div>
    <div v-else class="post-table">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border>
        <el-table-column
          type="selection"
          width="80"
          align="center"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          prop="semester_id"
          label="课堂id"
          min-width="50"
          align="center"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          prop="semester_name"
          label="课堂名称"
          min-width="100"
          align="center"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          prop="username"
          label="创建者姓名"
          min-width="100"
          align="center"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          label="课堂封面"
          min-width="100"
          align="center"
          header-align="center"
        >
          <template slot-scope="scope">
            <img :size="100"
                 :src="scope.row.cover"
                 style="width: 150px;object-fit: cover">
            </img>
          </template>
        </el-table-column>
        <el-table-column
          prop="start_time"
          label="开始时间"
          min-width="100"
          align="center"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="end_time"
          label="结束时间"
          min-width="100"
          align="center"
          header-align="center"
        >
        </el-table-column>
        <el-table-column label="操作" align="center"
                         header-align="center"
                         min-width="150">
          <template slot-scope="scope">
            <div class="juzhong" style="flex-direction: row">
              <el-button type="primary" size="small" @click="viewDetails(scope.row)">查看详情</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-divider></el-divider>
    <div class="juzhong">
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="formData.pageNum"
          :page-sizes="[10, 50, 100, 150]"
          :page-size="formData.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      :visible.sync="detailDialogVisible"
      title="课堂详情"
      width="60%"
      center
      @close="detailDialogVisible = false"
    >
      <el-form label-position="left" label-width="150px">
        <el-form-item label="课堂ID">
          <el-input v-model="currentSemester.semester_id" disabled></el-input>
        </el-form-item>
        <el-form-item label="课堂名称">
          <el-input v-model="currentSemester.semester_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建者姓名">
          <el-input v-model="currentSemester.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="课堂封面">
          <div class="avatar-container">
            <el-image v-if="currentSemester.cover" :src="currentSemester.cover" class="avatar"/>
            <i v-else class="el-icon-picture-outline"></i>
          </div>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-input v-model="currentSemester.start_time" disabled></el-input>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-input v-model="currentSemester.end_time" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {Message, MessageBox} from "element-ui";
import {getSemesters, deleteSemester} from "@/api/semester";

export default {
  name: 'Student',
  data() {
    return {
      loading: true,
      total: null,
      tableData: null,
      formData: {
        pageSize: 10,
        pageNum: 1,
        start_time: null,
        end_time: null,
        semester_name: null,
        username: null
      },
      pickerOptions: {
        shortcuts: [{
          text: '一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [end, start]);
          }
        }, {
          text: '一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [end, start]);
          }
        }, {
          text: '三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [end, start]);
          }
        }]
      },
      times: [],
      // 详情对话框相关
      detailDialogVisible: false,
      currentSemester: {}
    }
  },
  methods: {
    //处理时间
    handleTimes(val) {
      if (val && val.length === 2) {
        const formattedTimes = val.map(date => this.formatDate(date));
        this.formData.start_time = formattedTimes[0];
        this.formData.end_time = formattedTimes[1];
      } else {
        this.formData.start_time = null;
        this.formData.end_time = null;
      }
    },
    //转换时间格式
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    ClearPage() {
      this.formData = {
        pageSize: 10,
        pageNum: 1,
        start_time: null,
        end_time: null,
        semester_name: null,
        username: null
      };
      this.times = [];
    },
    handleClear() {
      this.ClearPage();
      this.fetchTable();
    },
    handleSizeChange(val) {
      this.formData.pageSize = val;
      this.fetchTable();
    },
    handleCurrentChange(val) {
      this.formData.pageNum = val;
      this.fetchTable();
    },
    async fetchTable() {
      this.loading = true;
      try {
        const rep = await getSemesters(this.formData);
        this.tableData = rep.items;
        this.total = rep.total;
      } catch (e) {
        console.log(e);
        Message.warning("查询无效！");
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      console.log(this.formData);
      this.fetchTable();
    },

    // 查看详情方法
    viewDetails(row) {
      // 复制对象避免引用问题
      this.currentSemester = {...row};
      console.log(this.currentSemester)
      this.detailDialogVisible = true;
    },

    // 删除单个课堂
    async handleDelete(row) {
      try {
        await MessageBox.confirm(
          `确定要删除课堂"${row.semester_name}"吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        // 调用删除接口
        await deleteSemester(row.semester_id);

        Message.success('删除成功');
        await this.fetchTable(); // 刷新表格
      } catch (error) {
        if (error !== 'cancel') {
          Message.error('删除失败，请重试');
          console.error('删除失败:', error);
        }
      }
    },

    // 批量删除
    async handleBatchDelete() {
      const selection = this.$refs.multipleTable.selection;

      if (selection.length === 0) {
        return Message.warning('请先选择要删除的课堂');
      }

      try {
        await MessageBox.confirm(
          `确定要删除选中的${selection.length}个课堂吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        // 批量删除逻辑
        const deletePromises = selection.map(item => deleteSemester(item.semester_id));
        await Promise.all(deletePromises);

        Message.success('批量删除成功');
        await this.fetchTable(); // 刷新表格
      } catch (error) {
        if (error !== 'cancel') {
          Message.error('删除失败，请重试');
          console.error('批量删除失败:', error);
        }
      }
    }
  },
  mounted() {
    this.fetchTable()
  }
}
</script>
<style scoped>
.detail-container {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

.detail-row {
  display: flex;
  align-items: center;
}

.detail-label {
  width: 120px;
  font-weight: bold;
  color: #606266;
}

.detail-value {
  flex: 1;
  color: #303133;
}
</style>
